package com.zhiche.lisa.tms.controller;

import com.alibaba.fastjson.JSON;
import com.lisa.json.JSONUtil;
import com.lisa.syslog.SysLogUtil;
import com.lisa.syslog.model.SysLogDataPo;
import com.zhiche.lisa.core.enums.CommonEnum;
import com.zhiche.lisa.core.enums.RedisLogTypeEnum;
import com.zhiche.lisa.core.enums.SystemEnum;
import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.core.supports.RestfulResponse;
import com.zhiche.lisa.oms.vo.LogExportPo;
import com.zhiche.lisa.tms.dao.model.ShipOrderItem;
import com.zhiche.lisa.tms.dao.model.ShipTask;
import com.zhiche.lisa.tms.dao.model.bo.ShipToByLicenseBO;
import com.zhiche.lisa.tms.dto.OTMEvent;
import com.zhiche.lisa.tms.dto.ReleaseDTO;
import com.zhiche.lisa.tms.dto.ShipParamDTO;
import com.zhiche.lisa.tms.service.IShipTaskService;
import com.zhiche.lisa.tms.vo.DepartureConfirmationVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 运输任务
 * </p>
 *
 * @author qichao
 * @since 2018-08-17
 */
@RestController
@RequestMapping("/shipTask")
@Api(value = "/shipTask", description = "运输任务接口", tags = {"运输任务接口"})
public class ShipTaskController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ShipmentController.class);
    @Autowired
    private IShipTaskService shipTaskService;

    @Value("${logRedis.isTest}")
    private boolean isTest;

    private static final String SHIP_DATA_FOR_BMS = "/shipTask/shipDataForBMS";

    @PostMapping(value = "/shippingTo")
    @ApiOperation(value = "运输任务运抵", notes = "运输任务运抵", produces = MediaType.APPLICATION_JSON_VALUE, response = RestfulResponse.class)
    @ApiResponses({@ApiResponse(code = 0, message = "success", response = String.class), @ApiResponse(code = -1, message = "操作失败", response = Object.class)})
    public RestfulResponse shippingTo(@RequestBody ShipToByLicenseBO shipToByLicenseBO,
                                      @RequestHeader("Authorization") String token) {
        LOGGER.info("ShipTaskController.shippingTo（运输任务运抵） params : {} ", shipToByLicenseBO.toString());
        RestfulResponse result = new RestfulResponse<>(0, "success", null);
        try {
            shipTaskService.shippingTo(shipToByLicenseBO, token);
        } catch (BaseException e) {
            LOGGER.error("ShipTaskController.shippingTo ERROR... ", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), e.getMessage(), null);
        } catch (Exception e) {
            LOGGER.error("ShipTaskController.shippingTo ERROR... ", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        }
        return result;
    }

    @PostMapping(value = "/departureConfirmation")
    @ApiOperation(value = "运输任务发车确认", notes = "运输任务发车确认", produces = MediaType.APPLICATION_JSON_VALUE, response = RestfulResponse.class)
    @ApiResponses({@ApiResponse(code = 0, message = "success", response = String.class), @ApiResponse(code = -1, message = "操作失败", response = Object.class)})
    public RestfulResponse<String> departureConfirmation(@RequestBody DepartureConfirmationVO departureConfirmation,
                                                         @RequestHeader("Authorization") String token) {
        LOGGER.info("ShipTaskController.departureConfirmation（运输任务发车确认） params : {} ", departureConfirmation);
        RestfulResponse<String> result = new RestfulResponse<>(0, "success", null);
        try {
            shipTaskService.departureConfirmation(departureConfirmation, token);
        } catch (BaseException e) {
            LOGGER.error("ShipTaskController.departureConfirmation ERROR... ", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), e.getMessage(), null);
        } catch (Exception e) {
            LOGGER.error("ShipTaskController.departureConfirmation ERROR... ", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        }
        return result;
    }

    /**
     * 接收wms 发运信息并组装BMS需求信息发送至BMS
     */
    @PostMapping("/shipDataForBMS")
    public RestfulResponse<Object> exportShip(@RequestBody ShipParamDTO dto) {
        RestfulResponse<Object> response = new RestfulResponse<>(0, "操作成功", null);
        try {

            //wms发运推送OMS，接收日志记录
//            addExportLogs(dto, SHIP_DATA_FOR_BMS, 2, 1, "");

            String result=shipTaskService.exportShip(dto);
            response.setData(result);

            //wms发运推送OMS，处理日志记录（成功）
//            addExportLogs(dto, SHIP_DATA_FOR_BMS, 3, 1, "");

        } catch (BaseException e) {
            //wms发运推送OMS，处理日志记录（失败）
//            addExportLogs(dto, SHIP_DATA_FOR_BMS, 3, 0, e.getMessage());

            LOGGER.error("ShipTaskController.departureConfirmation BaseException...{} ", e.getMessage());
            response.setCode(-1);
            response.setMessage(e.getMessage());
        } catch (Exception e) {
            //wms发运推送OMS，处理日志记录（失败）
//            addExportLogs(dto, SHIP_DATA_FOR_BMS, 3, 0, "系统异常");

            LOGGER.error("ShipTaskController.departureConfirmation ERROR...{} ", e);
            response.setCode(-1);
            response.setMessage("系统异常");
        }
        return response;
    }


    /**
     * 添加日志记录到日志系统
     */
    public void addExportLogs(ShipParamDTO otmEvent, String uri, Integer dataStatus, Integer isSuc, String errCont) {
        try {
            if (Objects.nonNull(otmEvent)) {
                String tableIdx = RedisLogTypeEnum.EVENT_EXPORT.getCode();
                String sourceSystem = SystemEnum.INTEGRATION.getCode();
                String targetSystem = SystemEnum.OMS.getCode();
                // 来源、目标系统表示
                // 目标API标示
                String key = sourceSystem + SystemEnum.UNDERLINE.getCode() + targetSystem;
                String fKey = uri + SystemEnum.UNDERLINE.getCode() + otmEvent.getExportKey() + SystemEnum.UNDERLINE.getCode() + otmEvent.getEventType() + SystemEnum.UNDERLINE.getCode() + dataStatus;
                String dtoJson = JSONUtil.toJsonStr(otmEvent);
                // 业务相关实体类
                LogExportPo logExportPo = new LogExportPo(sourceSystem, targetSystem, otmEvent.getEventType(), uri, otmEvent.getShipmentId(),
                        otmEvent.getOrderReleaseId(), otmEvent.getVin(), otmEvent.getOrderReleaseId(), otmEvent.getExportKey(), dtoJson, isSuc, errCont, 1, 0, dataStatus);
                SysLogDataPo sysLogDataPo = new SysLogDataPo(tableIdx, JSONUtil.toJsonStr(logExportPo));
                SysLogUtil.addSysLogs(key, fKey, sysLogDataPo, isTest);
            }
        } catch (Exception e) {
            LOGGER.error("事件导出回传otm，添加日志异常" + e.getMessage());
        }
    }


    @GetMapping(value = "/getShipTaskByCode/{code}")
    @ApiOperation(value = "根据Code得到列表", notes = "根据运输任务编号（Code）得到运输任务列表", produces = MediaType.APPLICATION_JSON_VALUE, response = RestfulResponse.class)
    @ApiResponses({@ApiResponse(code = 0, message = "success", response = String.class), @ApiResponse(code = -1, message = "操作失败", response = Object.class)})
    public RestfulResponse<ShipTask> getShipTaskByCode(@PathVariable String code) {
        LOGGER.info("ShipTaskController.getShipTaskByCode（根据运输任务编号得到运输任务列表） params : {} ", code);
        RestfulResponse<ShipTask> result = new RestfulResponse<>(CommonEnum.SUCCESS.getCode(), CommonEnum.SUCCESS.getText(), null);
        try {
            ShipTask shipTaskByCode = shipTaskService.getShipTaskByCode(code);
            result.setData(shipTaskByCode);
        } catch (BaseException e) {
            LOGGER.error("ShipTaskController.getShipTaskByCode ERROR... ", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), e.getMessage(), null);
        } catch (Exception e) {
            LOGGER.error("ShipTaskController.getShipTaskByCode ERROR... ", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        }
        return result;
    }

    @GetMapping(value = "/emptyToErp")
    @ApiOperation(value = "空放指令推送ERP", notes = "空放指令推送ERP", produces = MediaType.APPLICATION_JSON_VALUE, response = RestfulResponse.class)
    @ApiResponses({@ApiResponse(code = 0, message = "success", response = String.class), @ApiResponse(code = -1, message = "操作失败", response = Object.class)})
    public RestfulResponse emptyToErp(String instructNo) {
        LOGGER.info("ShipTaskController.emptyToErp（空放指令推送ERP） params : {} ", instructNo);
        RestfulResponse<String> result = new RestfulResponse<>(0, "success", null);
        try {
            shipTaskService.emptyToErps(instructNo);
        } catch (BaseException e) {
            LOGGER.error("ShipTaskController.emptyToErp ERROR... ", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), e.getMessage(), null);
        } catch (Exception e) {
            LOGGER.error("ShipTaskController.emptyToErp ERROR... ", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        }
        return result;
    }

    @GetMapping(value = "/getShipOrderItemByTaskId/{taskId}")
    @ApiOperation(value = "根据taskId得到订单详情列表", notes = "根据taskId得到订单详情列表", produces = MediaType.APPLICATION_JSON_VALUE, response = RestfulResponse.class)
    @ApiResponses({@ApiResponse(code = 0, message = "success", response = String.class), @ApiResponse(code = -1, message = "操作失败", response = Object.class)})
    public RestfulResponse<List<ShipOrderItem>> getShipOrderItemByTaskId(@PathVariable String taskId) {
        LOGGER.info("ShipTaskController.getShipOrderItemByTaskId（根据taskId得到订单详情列表） params : {} ", taskId);
        RestfulResponse<List<ShipOrderItem>> result = new RestfulResponse<>(CommonEnum.SUCCESS.getCode(), CommonEnum.SUCCESS.getText(), null);
        try {
            List<ShipOrderItem> shipOrderItems = shipTaskService.getShipOrderItemByTaskId(taskId);
            result.setData(shipOrderItems);
        } catch (BaseException e) {
            LOGGER.error("ShipTaskController.getShipOrderItemByTaskId ERROR... ", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), e.getMessage(), null);
        } catch (Exception e) {
            LOGGER.error("ShipTaskController.getShipOrderItemByTaskId ERROR... ", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        }
        return result;
    }

    @PostMapping(value = "/fleetDepartureConfirmation")
    @ApiOperation(value = "车队运输任务批量发车确认", notes = "车队运输任务批量发车确认", produces = MediaType.APPLICATION_JSON_VALUE, response = RestfulResponse.class)
    @ApiResponses({@ApiResponse(code = 0, message = "success", response = String.class), @ApiResponse(code = -1, message = "操作失败", response = Object.class)})
    public RestfulResponse<String> fleetDepartureConfirmation(@RequestBody List<DepartureConfirmationVO> departureConfirmations,
                                                         @RequestHeader("Authorization") String token) {
        LOGGER.info("ShipTaskController.fleetDepartureConfirmation（车队运输任务批量发车确认） params : {} ", departureConfirmations);
        RestfulResponse<String> result = new RestfulResponse<>(0, "success", null);
        try {
            if(null == departureConfirmations){return result;}
            for (DepartureConfirmationVO departureConfirmation : departureConfirmations){
                shipTaskService.departureConfirmation(departureConfirmation, token);
            }
        } catch (BaseException e) {
            LOGGER.error("ShipTaskController.fleetDepartureConfirmation ERROR... ", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), e.getMessage(), null);
        } catch (Exception e) {
            LOGGER.error("ShipTaskController.fleetDepartureConfirmation ERROR... ", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        }
        return result;
    }

    @PostMapping(value = "/fleetShippingTo")
    @ApiOperation(value = "车队运输任务批量运抵", notes = "车队运输任务批量运抵", produces = MediaType.APPLICATION_JSON_VALUE, response = RestfulResponse.class)
    @ApiResponses({@ApiResponse(code = 0, message = "success", response = String.class), @ApiResponse(code = -1, message = "操作失败", response = Object.class)})
    public RestfulResponse fleetShippingTo(@RequestBody List<ShipToByLicenseBO> shipToByLicenseBOs,
                                      @RequestHeader("Authorization") String token) {
        LOGGER.info("ShipTaskController.fleetShippingTo（车队运输任务批量运抵） params : {} ", shipToByLicenseBOs.toString());
        RestfulResponse result = new RestfulResponse<>(0, "success", null);
        try {
            if(null == shipToByLicenseBOs){return result;}
            for (ShipToByLicenseBO shipToByLicenseBO : shipToByLicenseBOs){
                shipTaskService.shippingTo(shipToByLicenseBO, token);
            }
        } catch (BaseException e) {
            LOGGER.error("ShipTaskController.fleetShippingTo ERROR... ", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), e.getMessage(), null);
        } catch (Exception e) {
            LOGGER.error("ShipTaskController.fleetShippingTo ERROR... ", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        }
        return result;
    }

    @PostMapping(value = "/shippingToToOtm")
    @ApiOperation(value = "重新推送运抵到OTM", notes = "重新推送运抵到OTM", produces = MediaType.APPLICATION_JSON_VALUE, response = RestfulResponse.class)
    @ApiResponses({@ApiResponse(code = 0, message = "success", response = String.class), @ApiResponse(code = -1, message = "操作失败", response = Object.class)})
    public RestfulResponse shippingToToOtm(@RequestParam("shipmentId") String shipmentId,@RequestHeader("Authorization") String token) {
        LOGGER.info("ShipTaskController.shippingToToOtm（重新推送运抵到OTM） params : {} ", shipmentId);
        RestfulResponse result = new RestfulResponse<>(0, "success", null);
        try {
                shipTaskService.shippingToToOtm(shipmentId, token);
        } catch (BaseException e) {
            LOGGER.error("ShipTaskController.shippingToToOtm ERROR... ", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), e.getMessage(), null);
        } catch (Exception e) {
            LOGGER.error("ShipTaskController.shippingToToOtm ERROR... ", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        }
        return result;
    }

    @PostMapping(value = "/shippingToToErp")
    @ApiOperation(value = "重新推送运抵到ERP", notes = "重新推送运抵到ERP", produces = MediaType.APPLICATION_JSON_VALUE, response = RestfulResponse.class)
    @ApiResponses({@ApiResponse(code = 0, message = "success", response = String.class), @ApiResponse(code = -1, message = "操作失败", response = Object.class)})
    public RestfulResponse shippingToToErp(@RequestParam("shipmentId") String shipmentId,@RequestHeader("Authorization") String token) {
        LOGGER.info("ShipTaskController.shippingToToErp（重新推送运抵到ERP） params : {} ", shipmentId);
        RestfulResponse result = new RestfulResponse<>(0, "success", null);
        try {
            shipTaskService.shippingToToERP(shipmentId);
        } catch (BaseException e) {
            LOGGER.error("ShipTaskController.shippingToToErp ERROR... ", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), e.getMessage(), null);
        } catch (Exception e) {
            LOGGER.error("ShipTaskController.shippingToToErp ERROR... ", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        }
        return result;
    }


    @PostMapping(value = "/updateShipOrderItem")
    @ApiOperation(value = "修改订单信息", notes = "修改订单信息", produces = MediaType.APPLICATION_JSON_VALUE, response = RestfulResponse.class)
    @ApiResponses({@ApiResponse(code = 0, message = "success", response = String.class), @ApiResponse(code = -1, message = "操作失败", response = Object.class)})
    public RestfulResponse updateShipOrder(@RequestBody ReleaseDTO releaseDTO) {
        LOGGER.info("ShipTaskController.updateShipOrder（修改订单信息） params : {} ", JSON.toJSONString(releaseDTO));
        RestfulResponse result = new RestfulResponse<>(0, "success", null);
        try {
            shipTaskService.updateShipOrder(releaseDTO);
        } catch (BaseException e) {
            LOGGER.error("ShipTaskController.updateShipOrder ERROR... {}", e.getMessage());
            result = new RestfulResponse<>(-1, e.getMessage(), null);
        } catch (Exception ex) {
            LOGGER.error("ShipTaskController.updateShipOrder ERROR... {}", ex.getMessage());
            result = new RestfulResponse<>(-1, "操作失败", null);
        }
        return result;
    }

    @GetMapping(value = "/getDevilerDate")
    @ApiOperation(value = "根据OR获取运抵时间", notes = "根据OR获取运抵时间", produces = MediaType.APPLICATION_JSON_VALUE, response = RestfulResponse.class)
    @ApiResponses({@ApiResponse(code = 0, message = "success", response = String.class), @ApiResponse(code = -1, message = "操作失败", response = Object.class)})
    public RestfulResponse<Map<String,Object>> getDevilerDate(@RequestParam String releaseGid) {
        LOGGER.info("ShipTaskController.getDevilerDate（根据OR获取运抵时间） params : {} ", JSON.toJSONString(releaseGid));
        RestfulResponse<Map<String,Object>> result = new RestfulResponse<>(0, "success", null);
        try {
            result.setData(shipTaskService.getDevilerDate(releaseGid));
        } catch (BaseException e) {
            LOGGER.error("ShipTaskController.getDevilerDate ERROR... {}", e.getMessage());
            result = new RestfulResponse<>(-1, e.getMessage(), null);
        } catch (Exception ex) {
            LOGGER.error("ShipTaskController.getDevilerDate ERROR... {}", ex.getMessage());
            result = new RestfulResponse<>(-1, "操作失败", null);
        }
        return result;
    }

}
